<template>
  <a-drawer
    :closable="false"
    :maskClosable="false"
    width="1000px"
    v-model:visible="state.visible"
    class="custom-class"
    title="定时发布时间设置"
    placement="right"
    zIndex="1000"
  >
    <a-alert type="info" showIcon>
      <template #description>
        <p v-if="$route.query.platform != 'douyin' && $route.query.platform != 'weixinshipinhao'">
          定时发布时间最早为当前时间的<span class="import_info_num">30</span
          >分钟后才能发布
        </p>
        <p v-if="$route.query.platform=='weixinshipinhao'">
          微信视频号平台定时发布规则：支持<span class="import_info_num">2</span
          >小时后及<span class="import_info_num">7</span>天内发定时发布
        </p>
        <p v-if="$route.query.platform == 'douyin'">
          抖音创作平台定时发布规则：支持<span class="import_info_num">2</span
          >小时后及<span class="import_info_num">14</span>天内发定时发布
        </p>
        <p v-if="$route.query.platform == 'douyin'">
          创建定时发送任务后，若需要修改定时时间，取消定时发布计划，需前往抖音创作中心进行操作！
        </p>
        <p>
          建议平台下单个账号每日设置的视频发布条数不超过<span
            class="import_info_num"
            >6</span
          >条 超出有可能影响视频流量
        </p>
      </template>
    </a-alert>
    <!-- 定时发布 -->
    <p>准备发布的视频条数:{{ videoPublishTotalCount }}</p>
    <div class="container">
      <a-form
        ref="regularReleseForm"
        class="regular_releseList"
        :model="state.timed_release_data"
      >
        <div
          class="regular_releseItem"
          v-for="(dateItem, dateIndex) in state.timed_release_data"
          :key="dateIndex"
        >
          <!-- 日期 -->
          <a-form-item
            style="margin-bottom: 15px"
            label="日期"
            :name="[dateIndex, 'date']"
            class="date_item"
            :rules="{
              required: true,
              message: '请选择日期',
            }"
          >
            <a-date-picker
              style="width: 240px"
              @change="changeDateItem(dateItem, dateIndex)"
              format="YYYY-MM-DD"
              v-model:value="dateItem.date"
              :disabledDate="disabledDate"
            />
            <a-button
              type="primary"
              style="margin-left: 20px; border-radius: 5px"
              @click="copyDateItem(dateItem, dateIndex)"
              >复制</a-button
            >
          </a-form-item>
          <!-- 时间段 -->
          <a-form
            style="margin-top: 5px"
            v-for="(timeItem, timeIndex) in dateItem.time"
            :key="timeIndex"
            ref="timeRefItem"
            :model="dateItem.time"
            layout="inline"
          >
            <a-form-item
              :label="`时间段${timeIndex + 1}`"
              :name="[timeIndex, 'time_period']"
              :rules="[
                { required: true, message: '预约开始时间请选择2小时后' },
                {
                  validator: validateTimeRange,
                  trigger: 'change',
                  timeItem: timeItem,
                  timeIndex: timeIndex,
                  dateItem: dateItem,
                  dateIndex: dateIndex,
                },
              ]"
            >
              <a-time-range-picker
                @openChange="
                  (open) => handleTimeChange(open, dateItem, timeItem)
                "
                :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [
                    dayjs('00:00', 'HH:mm'),
                    dayjs('11:59', 'HH:mm'),
                  ],
                }"
                style="width: 240px"
                v-model:value="timeItem.time_period"
                :disabled-time="disabledRangeTime"
                format="HH:mm"
              />
            </a-form-item>
            <a-form-item>
              <a-space>
                <!-- 增加时间点 -->
                <a-popconfirm
                  title="确定删除该时间点吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delTimeItemHandle(timeItem, timeIndex, dateIndex)"
                  @cancel="cancel"
                >
                  <delete-outlined />
                </a-popconfirm>
                <a-button
                  v-if="timeIndex == dateItem.time.length - 1"
                  class="add_btn"
                  size="small"
                  @click="addTimeItem(timeItem, timeIndex, dateIndex)"
                  style="
                    background: #cbcbcb;
                    color: #fff;
                    border-color: transparent;
                  "
                  ><plus-outlined
                /></a-button>
              </a-space>
            </a-form-item>
          </a-form>
          <a-divider
            style="height: 1px; background-color: #eeeeee"
            dashed
            v-if="dateIndex != state.timed_release_data.length - 1"
          />
          <!-- 删除日期项 -->
          <a-popconfirm
            title="确定删除该日期设置项吗?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="delDateItem(dateItem, dateIndex)"
            @cancel="cancel"
          >
            <a-button class="delItem_btn" style="background: transparent"
              ><cu-icon type="icon-jiantoushanchu"></cu-icon
            ></a-button>
          </a-popconfirm>
        </div>
      </a-form>
      <!-- 发布信息 -->
      <div class="dataItem_info">
        <p
          v-for="(dateItem, dateIndex) in state.timed_release_data"
          :key="dateIndex"
        >
          <template v-if="dateItem.date">
            {{ dateItem.date.format("YYYY-MM-DD")
            }}<span v-if="dateItem?.week">（{{ dateItem.week }}）</span>
            <template v-if="dateItem?.holiday?.length">
              <a-tag
                v-for="(holidayItem, holidayIndex) in dateItem.holiday"
                :key="holidayIndex"
                v-show="holidayItem"
                >{{ holidayItem }}</a-tag
              >
            </template>
          </template>
          预计每个账号发布
          <span style="color: var(--ss-primary-color); font-weight: 600"
            >{{ ExpectedNumber(dateItem) }}
            </span>条视频
        </p>
      </div>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="cancelHandle">取消</a-button>
        <a-button type="primary" @click="submitHandle">确定</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script setup>
import {
  PlusOutlined,
  CloudUploadOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  CloseOutlined,
  RightOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import moment from "moment";
import request from "../../../common/utils/request";
import { Modal } from "ant-design-vue";
import _ from "lodash";
import { Form, message } from "ant-design-vue";
import { useRoute } from "vue-router";
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  nextTick,
  ref,
  onMounted,
  createVNode,
} from "vue";
const props = defineProps({
  videoPublishTotalCount: {
    type: Number,
    default: 0,
  }, //预计发布视频数量
  accountListLength: {
    type: Number,
    default: 0,
  }, //账号数量
  getTitle:{
    type: String,
    default: '',
  }
});
const emit = defineEmits(["onClose"]);
const state = reactive({
  visible: false,
  timed_release_data: [
    {
      date: "",
      week: "",
      holiday: [],
      time: [
        {
          start_time: "",
          end_time: "",
          time_period: [],
        },
      ],
    },
  ],
  dataList: [],
});
const route = useRoute();
const showDrawer = (info) => {
  state.dataList = _.cloneDeep(info);
  state.visible = true;
  state.timed_release_data = _.cloneDeep(info);
};
// 禁用日期
const disabledDate = (current) => {
  const today = dayjs().startOf("day");
  if (route.query.platform == "douyin") {
    // 只能选择从今天开始的14天以内的日期
    const maxDate = today.add(14, "day");
    return current && (current < today || current >= maxDate);
  } else if (route.query.platform == "weixinshipinhao") {
    // 只能选择从今天开始的7天以内的日期
    const maxDate = today.add(disabledDateNum.value, "day");
    return current && (current < today || current >= maxDate);
  } else {
    // 只能选择今天及今天之后的日期
    return current && current < today;
  }
};
// 禁用时段
// const disabledTime = () => {
//   // 其他平台的禁用时间
//   if (route.query.platform != "douyin") {
//     const now = new Date();
//     const currentHour = now.getHours();
//     const currentMinute = now.getMinutes();

//     return {
//       disabledHours: () => {
//         return Array.from({ length: currentHour }, (_, i) => i);
//       },
//       disabledMinutes: (selectedHour) => {
//         if (selectedHour === currentHour) {
//           return Array.from({ length: currentMinute + 30 }, (_, i) => i);
//         }
//         return [];
//       },
//     };
//   } else {
//     // 抖音平台的禁用时间(如果选择的日期是今天，只能从当前时间2小时后开始选
//   }
// };
const disabledTime = () => {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();

  if (route.query.platform !== "douyin") {
    // 其他平台的禁用时间
    return {
      disabledHours: () => Array.from({ length: currentHour }, (_, i) => i),
      disabledMinutes: (selectedHour) => {
        if (selectedHour === currentHour) {
          return Array.from({ length: currentMinute + 30 }, (_, i) => i);
        }
        return [];
      },
    };
  } else {
    // 抖音平台的禁用时间
    const futureTime = dayjs().add(2, "hour");
    const futureHour = futureTime.hour();
    const futureMinute = futureTime.minute();

    return {
      disabledHours: () => Array.from({ length: futureHour }, (_, i) => i),
      disabledMinutes: (selectedHour) => {
        if (selectedHour === futureHour) {
          return Array.from({ length: futureMinute }, (_, i) => i);
        }
        return [];
      },
    };
  }
};

const range = (start, end) => {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
};
  const disabledRangeTime = () => {
    if(rangeTime.value){
      return {}
    }
    
    switch (props.getTitle) {
      case '抖音':
        return {
          disabledHours: () => range(0, moment().hour()+2),
          disabledMinutes: () => range(0, moment().minute()),
        };
      case '视频号':
        return {
          disabledHours: () => range(0, moment().hour()+2),
          disabledMinutes: () => range(0, moment().minute()),
        };
      default:
        return {
          disabledMinutes: () => range(0, moment().minute() + 30),        
        }
    }
   
  };

// 判断是否是今天
const isToday = (date) => {
  return dayjs(date).isSame(dayjs(), "day");
};
// 时间段校验
const validateTimeRange = (rule, value) => {
  return new Promise((resolve, reject) => {
    if (
      rule.timeItem.time_period &&
      rule.timeItem.time_period[0] &&
      rule.timeItem.time_period[1]
    ) {
      const { disabledHours, disabledMinutes } = disabledTime();
      const startTime = dayjs(rule.timeItem.time_period[0]);
      const endTime = dayjs(rule.timeItem.time_period[1]);
      // 检查日期是否为今天
      if (rule.dateItem.date) {
        const isTodayDate = isToday(rule.dateItem.date);
        // 如果日期是今天，使用 disabledTime 函数禁用非正常时间段
        if (isTodayDate) {
          if (
            disabledHours().includes(startTime.hour()) &&
            disabledHours().includes(endTime.hour())
          ) {
            reject("开始和结束时间为非正常时间段");
          }
          if (disabledHours().includes(startTime.hour())) {
            reject("开始时间为非正常时间段");
          }

          if (disabledHours().includes(endTime.hour())) {
            reject("结束时间为非正常时间段");
          }
          if (
            disabledMinutes(startTime.hour()).includes(startTime.minute()) &&
            disabledMinutes(endTime.hour()).includes(endTime.minute())
          ) {
            reject("开始和结束时间为非正常时间段");
          }
          if (disabledMinutes(startTime.hour()).includes(startTime.minute())) {
            reject("开始时间为非正常时间段");
          }

          if (disabledMinutes(endTime.hour()).includes(endTime.minute())) {
            reject("结束时间为非正常时间段");
          }
        }
      }

      if (endTime.isBefore(startTime)) {
        reject("开始时间不能大于结束时间");
        return;
      }

      const duration = endTime.diff(startTime, "minute");
      if (duration < 5) {
        reject("时间间隔不能小于5分钟");
        return;
      }
    }
    resolve();
  });
};
// 复制日期
const copyDateItem = async (item, index) => {
  // 预计可以发多少个时间段
  const TimeSlotsCount = Math.ceil(
    props.videoPublishTotalCount / props.accountListLength
  );
  // 当前已发布时间段总长度
  const timeLengthCount = state.timed_release_data.reduce((pre, cur) => {
    return pre + cur.time.length;
  }, 0);
  // 判断增加时间段之后视频数量是否不足
  if (timeLengthCount == TimeSlotsCount) {
    return message.error("待发布成片数量不足，请添加成片");
  }
  let currentDate = "";
  let newWeek = "";
  let newHoliday = [];
  // 找出 timed_release_data 中的最大日期
  let maxDate = null;
  state.timed_release_data.forEach((dataItem) => {
    if (
      dataItem.date &&
      (maxDate === null || dayjs(dataItem.date).isAfter(maxDate))
    ) {
      maxDate = dayjs(dataItem.date);
    }
  });
  if (maxDate) {
    currentDate = maxDate.add(1, "day"); // 将最大日期增加一天
    let params = {
      date: dayjs(currentDate).format("YYYY-MM-DD"),
    };

    try {
      const res = await request.get(
        "work_ai",
        "/user/filmrelease/holiday/get",
        params
      );
      newHoliday = res.result?.holiday || [];
      newWeek = res.result?.week || "";
    } catch (err) {
      console.log(err);
    }
  }
  const clonedData = _.cloneDeep(state.timed_release_data);
  console.log(TimeSlotsCount - timeLengthCount);
  clonedData.splice(index + 1, 0, {
    date: currentDate,
    week: newWeek,
    holiday: newHoliday,
    time: item.time.slice(0, TimeSlotsCount - timeLengthCount),
  });

  state.timed_release_data = clonedData;
};

// 日期change事件

const disabledDateNum = ref(dayjs().endOf("month").format('DD') - dayjs().format("DD") + 1)

const changeDateItem = (dateItem, dateIndex) => {
  if(props.getTitle =='视频号'){
    if(dayjs().endOf("month").format('DD') - dayjs().format('DD') <= 7 ){
      disabledDateNum.value = dayjs(dayjs().format("YYYY-MM-DD")).daysInMonth()
    }else{
      disabledDateNum.value = dayjs().endOf("month").format('DD') - dayjs().format("DD") + 1
    }
  }
 
  if (dateItem.date) {
    let params = {
      // date: dateItem.date.format("YYYY-MM-DD"),
      date: dayjs(dateItem.date).format("YYYY-MM-DD"),
    };
    request
      .get("/work_ai", "/user/filmrelease/holiday/get", params)
      .then((res) => {
        console.log(res);
        state.timed_release_data[dateIndex].holiday = res.result?.holiday;
        state.timed_release_data[dateIndex].week = res.result?.week;
        console.log(state.timed_release_data[dateIndex]);
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
// 删除日期项
const delDateItem = (item, index) => {
  if (state.timed_release_data.length <= 1) {
    message.error("至少保留一个日期设置");
    return;
  }
  state.timed_release_data.splice(index, 1);
  message.success("删除成功");
};
// 添加时间段
const addTimeItem = (timeItem, timeIndex, dateIndex) => {
  // 预计可以发多少个时间段
  const TimeSlotsCount = Math.ceil(
    props.videoPublishTotalCount / props.accountListLength
  );
  // 当前已发布时间段总长度
  const timeLengthCount = state.timed_release_data.reduce((pre, cur) => {
    return pre + cur.time.length;
  }, 0);
  // 判断增加时间段之后视频数量是否不足
  if (timeLengthCount + 1 > TimeSlotsCount) {
    return message.error("待发布成片数量不足，请添加成片");
  }
  // 判断是否有账号发布到成片
  if (
    (timeLengthCount + 1) * props.accountListLength >
    props.videoPublishTotalCount
  ) {
    message.warning("成片数量不足，可能无法均分到每个账号");
  }
  // 预计发布视频总数量
  let newPeriodTime = [];
  if (timeItem.time_period.length > 1) {
    let newStartTime = timeItem.time_period[1]; // 新的开始时间
    let newEndTime = dayjs(timeItem.time_period[1], "HH:mm").add(1, "hour"); //新的结束时间
    // 判断新的开始时间或者新的结束时间有没有出现00:mm的情况，有的话就提示暂无可添加时间段
    if (newEndTime.format("HH") == "00") {
      return message.warning("暂无可增加时间段");
    }
    newPeriodTime = [newStartTime, newEndTime]; // 创建新的时间段,依照上一个结束时间再自动前进一个小时
  }
  const clonedData = _.cloneDeep(state.timed_release_data); // 深拷贝数据
  clonedData[dateIndex].time.splice(timeIndex + 1, 0, {
    time_period: newPeriodTime,
    start_time: "",
    end_time: "",
  });
  state.timed_release_data = clonedData; // 更新数据
};

// 时间段选择事件
const rangeTime= ref(false)
const handleTimeChange = (open, dateItem, timeItem) => {
  // 判断是否是今天
  if(!isToday(dateItem.date)){
    rangeTime.value = true
  }else{
    rangeTime.value = false
  }

  if (open) {
    // 判断时间选择器是否打开
  } else {
    // 判断单个账号成片发布间隔是否小于30分钟
    if (timeItem.time_period.length > 1) {
      // 预计可发多少个时间段
      const TimeSlotsCount =
        props.videoPublishTotalCount / props.accountListLength;
      // 当前时间段总数
      const timeLengthCount = state.timed_release_data.reduce((acc, cur) => {
        return acc + cur.time.length;
      }, 0);
      //  预计每个时间段每个账号发布成片数量
      const ReleasesPerAccount = TimeSlotsCount / timeLengthCount;
      // 判断发布时间间隔
      const intervalInMinutes =
        timeItem.time_period[1].diff(timeItem.time_period[0], "minute") /
        ReleasesPerAccount; // 计算每个视频的发布间隔时间（分钟）
      console.log(intervalInMinutes, "jmzxmzmmintervalInMinutes");
      if (intervalInMinutes < 30) {
        message.warning("单个账号发布发布成片间隔小于30分钟，注意账号风险");
      }
    }
  }
};
// 删除时间段
const delTimeItemHandle = (timeItem, timeIndex, dateIndex) => {
  if (state.timed_release_data[dateIndex].time.length <= 1) {
    return message.error("每个日期至少保留一个时间段");
  } else {
    state.timed_release_data[dateIndex].time.splice(timeIndex, 1);
    message.success("删除成功");
  }
};
/**
 * @description 预计每天每个账号发送多少条视频
 * @description 单个时间段的单个账号视频发布数量 = (视频数量除以账号数量，含小数则加一，
 * 结果再除以时间段数量，含小数则加1)
 * @description 每个时间段时长 / 单个时间段的单个账号视频发布数量 ，小于30秒，则进行提醒
 *
 */
const ExpectedNumber = (dateItem) => {
  // 预计可发多少个时间段
  const TimeSlotsCount = props.videoPublishTotalCount / props.accountListLength;
  // 当前时间段总数
  const timeLengthCount = state.timed_release_data.reduce((acc, cur) => {
    return acc + cur.time.length;
  }, 0);

  console.log(state.timed_release_data,'log数据');
  
  
  //  预计每个时间段每个账号发布成片数量
  const ReleasesPerAccount = TimeSlotsCount / timeLengthCount;
  // 预计每天每个账号可以发布的视频数量
  const min_ExpectedCount = Math.floor(ReleasesPerAccount * dateItem.time.length);
  const max_ExpectedCount = Math.ceil(ReleasesPerAccount * dateItem.time.length);

  const showText = min_ExpectedCount == max_ExpectedCount ? min_ExpectedCount : `${min_ExpectedCount}-${max_ExpectedCount}`
  return showText;
};
let regularReleseForm = ref(null); //定时发布日期表单实例
let timeRefItem = ref(null); //定时发布时间段表单实例

const submitHandle = _.debounce(() => {
  let validateArr = [];
  let regularFormValidate = regularReleseForm.value
    ? regularReleseForm.value.validate()
    : Promise.resolve();
  let timeRefValidate = timeRefItem.value
    ? Promise.all(timeRefItem.value.map((item) => item.validate()))
    : Promise.resolve([]);
  let publishTimeFormValidateList = [regularFormValidate, timeRefValidate];
  validateArr.push(Promise.all(publishTimeFormValidateList));
  Promise.all(validateArr)
    .then((res) => {
      const duplicates = [];
      let repeatList = []; //重复列表
      const dateSet = new Set();
      let timedReleaseData = JSON.parse(
        JSON.stringify(state.timed_release_data)
      );
      for (let i = 0; i < timedReleaseData.length; i++) {
        const date = timedReleaseData[i].date;
        // 检查是否已经存在相同的日期
        if (dateSet.has(date)) {
          duplicates.push(i + 1); // 将索引添加到重复数组中，加1是为了从1开始计数
          repeatList.push(timedReleaseData[i]);
        } else {
          dateSet.add(date); // 将日期添加到集合中
        }
      }
      if (duplicates.length > 0) {
        const duplicateDates = [
          ...new Set(
            repeatList.map((dateItem) =>
              dayjs(dateItem.date).format("YYYY-MM-DD")
            )
          ),
        ]; // 获取所有重复的日期并去重
        const duplicateDatesString = duplicateDates.join("/ "); // 将日期转为字符串
        const duplicateIndexes = duplicates.join("/");
        return message.error(
          `日期 ${duplicateDatesString}存在重复，请重新设置第${duplicateIndexes}组日期`
        );
      } else {
        emit("onClose", state.timed_release_data);
        state.visible = false;
      }
    })
    .catch((err) => {});
}, 500);
// 初始化数据
const initData = () => {
  regularReleseForm.value && regularReleseForm.value.resetFields();
  timeRefItem.value && timeRefItem.value.map((item) => item.resetFields());
  state.timed_release_data = state.dataList;
};
// 取消
const cancelHandle = () => {
  let isChange = _.isEqual(state.timed_release_data, state.dataList);
  console.log(isChange);
  if (isChange) {
    state.visible = false;
    initData();
  } else {
    Modal.confirm({
      title: "提示",
      icon: createVNode(ExclamationCircleOutlined),
      content: "当前页操作还未保存，直接离开数据不会保存和更新",
      cancelText: "取消",
      okText: "确定",
      onOk() {
        state.visible = false;
        initData();
      },
      onCancel() {},
    });
  }
};
defineExpose({
  showDrawer,
});
</script>

<style lang="less" scoped>
.container {
  display: flex;

  // 定时发布时间设置列表
  .regular_releseList {
    margin-right: 15px;

    :deep(.ss-form-item-label) {
      width: 90px !important;
    }

    .regular_releseItem {
      margin-top: 10px;
      position: relative;
      padding-left: 50px;

      .delItem_btn {
        position: absolute;
        display: flex;
        align-items: center;
        top: 0;
        left: 0;
        border: transparent;
        width: 40px;
        font-size: 24px;
        color: rgb(180, 180, 180);
        justify-content: center;
      }
    }
  }

  // 发布信息
  .dataItem_info {
    background: #eeeeee;
    margin-top: 10px;
    flex: 1;
    padding: 10px 0 0 10px;
  }
}
.import_info_num {
  color: red;
  font-weight: 600;
  margin: 0 2px;
}
</style>
